<template>
  <div>
    <el-dialog v-bind="$attrs" v-on="$listeners" @open="onOpen" @close="onClose" @title="title">
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
          <el-col :span="18">
            <el-form-item label="策略名" prop="strategyName">
              <el-input v-model="formData.strategyName" placeholder="请输入策略名" clearable
                :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="18">
          <el-form-item label="所属公司" prop="deptId">
            <el-select v-model="formData.deptId" placeholder="请选择所属公司" clearable
              :style="{width: '100%'}"  collapse-tags>
              <el-option v-for="(item, index) in deptOptions" :key="index" :label="item.deptName" 
                :value="item.deptId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
          <el-col :span="18">
            <el-form-item label="通行人员" prop="accessTag">
              <el-select v-model="formData.accessTag" placeholder="请选择通行人员" clearable
                :style="{width: '100%'}"  multiple collapse-tags>
                <el-option v-for="(item, index) in accessTagOptions" :key="index" :label="item.tagName"
                  :value="item.tagId" :disabled="item.disabtagIdled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="通行设备" prop="accessDevice">
              <el-select v-model="formData.accessDevice" placeholder="请选择通行设备" clearable
                :style="{width: '100%'}"  multiple collapse-tags>
                <el-option v-for="(item, index) in accessDeviceOptions" :key="index" :label="item.deviceName"
                  :value="item.deviceId" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="通行规则" prop="accessRule">
              <el-radio-group v-model="formData.accessRule" size="medium" @change="changeAccessRule()">
                <el-radio v-for="(item, index) in accessRuleOptions" :key="index" :label="item.value"
                  :disabled="item.disabled">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="时间规则" prop="timeRule" v-if="isVisible.isTimePeriod" >
              <el-radio-group v-model="formData.timeRule" size="medium"  @change="changeTimeRule()">
                <el-radio v-for="(item, index) in timeRuleOptions" :key="index" :label="item.value"
                  :disabled="item.disabled">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="选择周日期" prop="accessWeek" v-if="isVisible.isWeek">
              <el-checkbox-group v-model="formData.accessWeek" size="mini">
                <el-checkbox-button v-for="(item, index) in accessWeekOptions" :key="index" :label="item.value"
                  :disabled="item.disabled">{{item.label}}</el-checkbox-button>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="选择日期" prop="accessDate" v-if="isVisible.isDate">
              <el-date-picker type="daterange" v-model="formData.accessDate" format="yyyy-MM-dd" 
                value-format="yyyy-MM-dd" :style="{width: '100%'}" start-placeholder="开始日期"
                end-placeholder="结束日期" range-separator="至" clearable></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="通行时间" prop="accessTime" v-if="isVisible.isTimePeriod">
              <el-time-picker v-model="formData.accessTime" is-range format="HH:mm:ss" value-format="HH:mm:ss" arrow-control
                :style="{width: '100%'}" start-placeholder="开始时间" end-placeholder="结束时间" range-separator="至"
                clearable></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="生效日期" prop="startDate">
              <el-date-picker
                v-model="formData.startDate"
                type="date"
                :style="{width: '100%'}"
                placeholder="选择生效日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注"
                :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="id" prop="id" v-show>
              <el-input v-model="formData.id" placeholder="请输入id" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="策略Id" prop="strategyId" v-show>
              <el-input v-model="formData.strategyId" placeholder="请输入策略Id" clearable
                :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { deviceApi } from "@/api/business/device";
import { strategyApi } from "@/api/business/strategy";
import { getTagAllList } from "@/api/business/tag";
import {whiteApi} from "@/api/system/white";
export default {
  inheritAttrs: false,
  components: {},
  props: {
    // 是否为更新表单
    isUpdate: {
      type: Boolean,
      default: false
    },
    // 更新的表单数据对象
    updateData: {
      type: Object
    }
  },
  data() {
    return {
      title:'',
      formData: {
        strategyName: undefined,
        accessTag: [],
        accessDevice: [],
        accessRule: 'all',
        timeRule: 'week',
        accessWeek: [],
        accessDate: null,
        accessTime:  ["00:00:00", "23:59:59"],
        startDate: new Date(),
        remark: undefined,
        id: undefined,
        strategyId: undefined,
        deptId: null
      },
      isVisible:{
          isTimePeriod : false,
          isWeek : false,
          isDate : false
      },
      rules: {
        strategyName: [{
          required: true,
          message: '请输入策略名',
          trigger: 'blur'
        }],
        deptId: [
          { required: true, message: "请选择所属公司", trigger: "blur" }
        ],
        accessTag: [],
        accessDevice: [],
        accessRule: [],
        timeRule: [],
        accessWeek: [],
        accessDate: [],
        accessTime: [],
        startDate: [],
        remark: [],
        id: [],
        strategyId: [],
      },
      accessTagOptions: [{
        "label": "选项一",
        "value": 1
      }, {
        "label": "选项二",
        "value": 2
      }],
      accessDeviceOptions: [{
        "label": "选项一",
        "value": 1
      }, {
        "label": "选项二",
        "value": 2
      }],
      accessRuleOptions: [{
        "label": "全时段",
        "value": "all"
      }, {
        "label": "指定时段",
        "value": "assign"
      }],
      timeRuleOptions: [{
        "label": "星期",
        "value": "week"
      }, {
        "label": "日期",
        "value": "date"
      }],
      accessWeekOptions: [{
        "label": "周一",
        "value": '1'
      }, {
        "label": "周二",
        "value": '2'
      }, {
        "label": "周三",
        "value": '3'
      }, {
        "label": "周四",
        "value": '4'
      }, {
        "label": "周五",
        "value": '5'
      }, {
        "label": "周六",
        "value": '6'
      }, {
        "label": "周日",
        "value": '7'
      }],
      deptOptions: []
    }
  },
  computed: {},
  watch: {
    updateData(newValue, oldValue) {
      if (this.isUpdate) {
        this.$nextTick(() => {
           // 通行人员通行设备回显
          for (let k in this.formData) {
            if ("accessWeek" === k || "accessDate" === k || "accessTime" === k) {
              this.$set(this.formData, k, JSON.parse(newValue[k]));
            } else if ("deptId" === k) {
              this.$set(this.formData, k, Number(newValue[k]));
            } else {
              this.$set(this.formData, k, newValue[k]);
            }
          }
          if(this.formData.accessRule=="assign"){
            this.isVisible.isTimePeriod = true;
            if(this.formData.timeRule == "week"){
              this.formData.isWeek = true;
              this.isVisible.isWeek = true
            }else{
              this.formData.isDate = true;
              this.isVisible.isDate = true
            }
          }
        })
        
      }
    }
  },
  created() {
    this.selectOption()
    this.createDeptOptions();
  },
  mounted() {},
  methods: {
    createDeptOptions(){
      whiteApi.getDeptOptions().then(response => {
        this.deptOptions = response.data;
      });
    },
    selectOption(){
       deviceApi
        .getDeviceAllList()
        .then(res => {
          this.accessDeviceOptions = res.data;
        })
        .catch(error => {
          console.log(error);
        });
      
        getTagAllList()
        .then(res => {
          this.accessTagOptions = res.data;
        })
        .catch(error => {
          console.log(error);
        });
    },
    onOpen() {
      if(!this.isUpdate) {
        this.onClose();
      }
    },
    onClose() {
      this.$refs['elForm'].resetFields();
      // this.isUpdate = false;
      this.isVisible.isTimePeriod = false;
      this.formData.accessDate = null;
      this.formData.accessWeek = [];
      this.isVisible.isWeek = false;
      this.isVisible.isDate = false;
    },
    close() {
      this.$emit('update:visible', false)
    },
    handleConfirm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        if (this.isUpdate) {
          this.update();
        }else{
          this.add();
        }
      })
    },
    update(){
      strategyApi
        .updateStrategy(this.formData)
        .then(res => {
          this.$message.success(res.msg);
          this.close();
          this.$parent.getList();
        })
        .catch(error => {
          console.log(error);
        });
    },
    add(){
       strategyApi
        .addStrategy(this.formData)
        .then(res => {
          this.$message.success(res.msg);
          this.close();
          this.$parent.getList();
        })
        .catch(error => {
          console.log(error);
        });
    },
    changeAccessRule(){
        this.isVisible.isTimePeriod=!this.isVisible.isTimePeriod;
        if(this.isVisible.isTimePeriod){
            this.formData.timeRule= 'week',
            this.isVisible.isWeek = true;
            this.isVisible.isDate = false;
        }else{
            this.formData.accessDate = null;
            this.formData.accessWeek = [];
            this.isVisible.isWeek = false;
            this.isVisible.isDate = false;
        }
    },
    changeTimeRule(){
       this.isVisible.isWeek = !this.isVisible.isWeek;
       if(this.isVisible.isWeek){
         this.formData.accessDate = null;
       }else{
         this.formData.accessWeek = [];
       }
       this.isVisible.isDate = !this.isVisible.isDate;
    },
    setTagAndDevice(strategyId) {
      strategyApi
        .getTagAndDevice(strategyId)
        .then(res => {
          let data = JSON.parse(JSON.stringify(res.data))
          if(data.tags!=null && data.tags!=''){
            this.formData.accessTag = data.tags;
          }

          if(data.devices!=null && data.devices!=''){
            this.formData.accessDevice = data.devices;
          }
         
        })
        .catch(error => {
          console.log(error);
        });
    }
  }
}

</script>
<style>
</style>
